import "../common/common.scss"
import "./curve.scss"
import {
    Dom,
    CommonCaptcha,
    closeTips,
    down,
    drawBgImage,
    initConfig,
    showTips,
    destroyEvent
} from "../common/common.js"

/**
 * 滑动验证码
 */

const TYPE = "CURVE"

function getTemplate(styleConfig) {
    return `
<div id="tianai-captcha" class="tianai-captcha-slider">
    <div class="slider-tip">
        <span id="tianai-captcha-slider-move-track-font" style="font-size: ${styleConfig.i18n.slider_title_size}">${styleConfig.i18n.curve_title}</span>
    </div>
    <div class="content">
        <div class="bg-img-div">
            <img id="tianai-captcha-slider-bg-img" src="" alt/>
            <canvas id="tianai-captcha-slider-bg-canvas"></canvas>
            <canvas id="tianai-captcha-curve-bg-canvas"></canvas>
            <div class="tianai-captcha-curve-ball-div" id="tianai-captcha-curve-ball-div-left"></div>
            <div class="tianai-captcha-curve-ball-div" id="tianai-captcha-curve-ball-div-right"></div>
        </div>
        <div class="tianai-captcha-tips" id="tianai-captcha-tips"></div>
    </div>
    <div class="slider-move">
        <div class="slider-move-track">
            <div id="tianai-captcha-slider-move-track-mask"></div>
            <div class="slider-move-shadow"></div>
        </div>
        <div class="slider-move-btn" id="tianai-captcha-slider-move-btn">
                 <span></span>
        <span></span>
        <span></span>
         <span></span>
        </div>
    </div>

</div>
`
}

class Curve extends CommonCaptcha {
    constructor(divId, styleConfig) {
        super();
        this.boxEl = Dom(divId);
        this.styleConfig = styleConfig;
        this.type = TYPE;
        this.currentCaptchaData = {}
    }

    init(captchaData, endCallback, loadSuccessCallback) {
        // 重载样式
        this.destroy();
        this.boxEl.append(getTemplate(this.styleConfig));
        this.el = this.boxEl.find("#tianai-captcha");
        this.loadStyle();
        // 按钮绑定事件
        this.el.find("#tianai-captcha-slider-move-btn").mousedown(down);
        this.el.find("#tianai-captcha-slider-move-btn").touchstart(down);
        // 绑定全局
        window.currentCaptcha = this;
        // 载入验证码
        this.loadCaptchaForData(this, captchaData);
        this.endCallback = endCallback;
        if (loadSuccessCallback) {
            // 加载成功
            loadSuccessCallback(this);
        }
        return this;
    }

    showTips(msg, type, callback) {
        showTips(this.el, msg, type, callback)
    }

    closeTips(callback) {
        closeTips(this.el, callback)
    }

    destroy() {
        const existsCaptchaEl = this.boxEl.children("#tianai-captcha");
        if (existsCaptchaEl) {
            existsCaptchaEl.remove();
        }
        destroyEvent();
    }

    doMove() {
        const moveX = this.currentCaptchaData.moveX;
        this.el.find("#tianai-captcha-slider-move-btn").css("transform", "translate(" + moveX + "px, 0px)")
        this.el.find("#tianai-captcha-slider-move-track-mask").css("width", moveX + "px")
        this.drawBezier(moveX);
    }

    loadStyle() {
        let sliderImg = "";
        let moveTrackMaskBorderColor = "#00f4ab";
        let moveTrackMaskBgColor = "#a9ffe5";
        const styleConfig = this.styleConfig;
        if (styleConfig) {
            sliderImg = styleConfig.btnUrl;
            moveTrackMaskBgColor = styleConfig.moveTrackMaskBgColor;
            moveTrackMaskBorderColor = styleConfig.moveTrackMaskBorderColor;
        }
        this.el.find(".slider-move .slider-move-btn").css("background-image", "url(" + sliderImg + ")");
        // this.el.find("#tianai-captcha-slider-move-track-font").text(title);
        this.el.find("#tianai-captcha-slider-move-track-mask").css("border-color", moveTrackMaskBorderColor);
        this.el.find("#tianai-captcha-slider-move-track-mask").css("background-color", moveTrackMaskBgColor);
    }

    loadCaptchaForData(that, data) {
        const bgImg = that.el.find("#tianai-captcha-slider-bg-img");
        bgImg.attr("src", data.captcha.backgroundImage);
        const initFn = (THIS) => {
            that.currentCaptchaData = initConfig(bgImg.width(), bgImg.height(), 0, 0, 300 - 63);
            that.currentCaptchaData.currentCaptchaId = data.id;
            // 重组
            drawBgImage(data.captcha, "tianai-captcha-slider-bg-canvas", "tianai-captcha-slider-bg-img", 50);

            const canvas = that.el.find("#tianai-captcha-curve-bg-canvas").getTarget();
            canvas.width = bgImg.width();
            canvas.height = bgImg.height();
            let p = data.captcha.data.p;
            let posOrder = [];
            for (let i = 0; i < 5; i++) {
                let index = Math.pow(2, i);
                posOrder.unshift(p.charAt(index));
                p = p.substring(0, index) + p.substring(index + 1);
            }
            let posArr = [];
            let index = -1;
            while ((index = p.lastIndexOf(".")) > 0) {
                let pos = p.substring(index - 1);
                posArr.unshift(pos);
                p = p.substring(0, index - 1);
            }
            let sortPosArr = [];
            for (let i = 0; i < 5; i++) {
                posOrder.forEach((item, index) => {
                    if (parseInt(item) === i) {
                        sortPosArr.push(posArr[index]);
                    }
                });
            }
            this.canvas = {};

            THIS.canvas.width = bgImg.width();
            THIS.canvas.height = bgImg.height();
            THIS.canvas.leftX = sortPosArr[0] * this.canvas.width;
            THIS.canvas.leftY = sortPosArr[1] * this.canvas.height;
            THIS.canvas.rightX = sortPosArr[2] * this.canvas.width;
            THIS.canvas.rightY = sortPosArr[3] * this.canvas.height;
            THIS.canvas.ctrlY = sortPosArr[4] * this.canvas.height;


            that.el.find("#tianai-captcha-curve-ball-div-left").css({
                left: this.canvas.leftX - 8 + "px",
                top: this.canvas.leftY - 8 + "px",
                display: "block"
            });
            that.el.find("#tianai-captcha-curve-ball-div-right").css({
                left: this.canvas.rightX - 8 + "px",
                top: this.canvas.rightY - 8 + "px",
                display: "block"
            });

            THIS.drawBezier(0);
        }
        if (bgImg.width() > 0) {
            bgImg.on("load", () => {
                initFn(this);
            });
        } else {
            setTimeout(() => {
                initFn(this);
            }, 200)
        }
    }

    drawBezier(x) {
        const canvas = this.el.find("#tianai-captcha-curve-bg-canvas").getTarget();
        const cxt = canvas.getContext("2d");
        cxt.beginPath();
        cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
        cxt.strokeStyle = "rgba(255,255,255,0.75)";
        cxt.lineWidth = 5;
        cxt.shadowColor = "rgb(0,0,0)";
        // 设置模糊距离为10
        cxt.shadowBlur = 2;
        cxt.moveTo(this.canvas.leftX, this.canvas.leftY);
        cxt.bezierCurveTo(x, this.canvas.ctrlY, x, this.canvas.ctrlY, this.canvas.rightX, this.canvas.rightY);
        cxt.stroke();
    }

}

export default Curve;
